<template>
  <div class="flex items-start bg-[#fff] rounded-[1.25rem] p-[1.5rem] " :class="{ 'shadow-[0px_2px_8px_0px_#0F172A0A]': props.border }" :style="{ border: props.border ? '1px solid #F3F4F6' : 'none' }">
    <!-- 作者头像 -->
    <div class="w-[2.5rem] h-[2.5rem] rounded-full bg-[#F3F4F6] flex-shrink-0 cursor-pointer" @click="handleAuthorClick(article.author)">
      <img :src="article.authorAvatar" alt="" class="w-full h-full rounded-full" />
    </div>
    
    <div class="pl-[1rem] flex flex-col gap-[0.5rem] w-[calc(100%-2.5rem)]">
      <!-- 作者信息 -->
      <div class="flex gap-[0.5rem] justify-between items-center">
        <div class="flex flex-col">
          <p class="flex items-center">
            <span class="text-[1rem] font-[Inter] font-medium leading-[1.5rem] text-[#000000] mr-[0.5rem]">
              {{ article.author }}
            </span>
            <span class="text-[1rem] font-[Inter] font-normal leading-[1.25rem] text-[#2563EB] flex">
              Lv.{{ article.authorLevel }}
            </span>
          </p>
          <p class="flex">
            <span class="text-[0.875rem] font-[Inter] font-normal leading-[1.25rem] text-[#9CA3AF]">
              {{ article.releaseTime }}
            </span>
          </p>
        </div>
        
        <!-- 更多操作按钮 -->
        <el-dropdown trigger="click" @command="handleCommand" placement="bottom-end">
          <div class="cursor-pointer">
            <img src="/public/icon/more.png" alt="" class="w-[1rem] h-[0.35rem]">
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <!-- 管理员可见选项 -->
              <template v-if="isAdmin">
                <el-dropdown-item :command="{type: 'changeCategory', id: article.id}">修改分类</el-dropdown-item>
                <el-dropdown-item :command="{type: 'addTag', id: article.id}">添加标签</el-dropdown-item>
                <el-dropdown-item :command="{type: 'setTop', id: article.id}">设为置顶</el-dropdown-item>
                <el-dropdown-item :command="{type: 'setEssence', id: article.id}">设为精华</el-dropdown-item>
                <el-dropdown-item :command="{type: 'collect', id: article.id}">收藏</el-dropdown-item>
                <el-dropdown-item :command="{type: 'takeDown', id: article.id}" class="text-[#ff4d4f]">下架</el-dropdown-item>
              </template>
              <!-- 普通用户可见选项 -->
              <template v-else>
                <el-dropdown-item :command="{type: 'setEssence', id: article.id}">申请加精</el-dropdown-item>
                <el-dropdown-item :command="{type: 'collect', id: article.id}">收藏</el-dropdown-item>
                <el-dropdown-item :command="{type: 'complaint', id: article.id}">投诉</el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      
      <!-- 文章标题 -->
      <div class="text-[1.125rem] font-[Inter] font-medium leading-[1.75rem] text-[#000000]">
        {{ article.title }}
      </div>
      
      <!-- 文章描述 -->
      <div class="text-[1rem] font-[Inter] font-normal leading-[1.5rem] text-[#4B5563]">
        {{ article.description }}
      </div>
      
      <!-- 查看详情 -->
      <div class="text-[0.875rem] font-[Inter] font-normal leading-[1.25rem] text-[#2563EB] cursor-pointer" @click="handlePostClick(article.id)">
        查看详情
      </div>
      
      <!-- 附件 -->
      <div v-if="article.files && article.files.length > 0">
        <div class="flex flex-col gap-[0.5rem]">
          <div 
            v-for="(file, index) in article.files.slice(0, 9)" 
            :key="index"
            class="flex items-center rounded-[0.5rem] border border-[#E5E7EB] hover:bg-[#F9FAFB] cursor-pointer"
            @click="handleFileClick(file)"
          >
            <img :src="getFileIcon(file)" class="w-[1.25rem] h-[1.5rem] mr-[0.75rem]" alt="file" />
            <div class="flex-1 truncate">{{ getFileName(file) }}</div>
          </div>
          <!-- <div v-if="article.files.length > 9" class="text-[0.75rem] font-[Inter] font-normal leading-[1rem] text-[#6B7280] text-center">
            还有 {{ article.files.length - 9 }} 个附件
          </div> -->
        </div>
      </div>
      
      <!-- 图片 -->
      <div v-if="article.images && article.images.length > 0">
        <!-- 单张图片 -->
        <div v-if="article.images.length === 1" class="w-[16rem] h-[9rem] overflow-hidden rounded-[0.25rem]">
          <el-image 
            :src="article.images[0]" 
            fit="cover"
            class="w-[full] h-[full]" 
            style="aspect-ratio: 16/9;"
            :preview-src-list="article.images"
            :initial-index="0"
            preview-teleported
          />
        </div>
        <!-- 多张图片 -->
        <div v-else class="grid grid-cols-3 gap-[0.5rem] max-w-[25.375rem]">
          <div 
            v-for="(image, index) in article.images.slice(0, 9)" 
            :key="index"
            class="aspect-square w-[8.125rem] h-[8.125rem] overflow-hidden"
          >
            <el-image 
              :src="image" 
              fit="cover"
              class="w-full h-full"
              :preview-src-list="article.images"
              :initial-index="index"
              preview-teleported
              hide-on-click-modal
            />
          </div>
        </div>
      </div>
      
      <!-- 标签 -->
      <div v-if="article.tags && article.tags.length > 0" class="flex flex-wrap gap-[0.5rem]">
        <span 
          v-for="tag in article.tags" 
          :key="tag"
          class="px-[0.75rem] py-[0.25rem] border-[1px] border-solid border-[#2563EB] rounded-[0.3rem] text-[0.75rem] font-[Inter] font-normal leading-[1rem] text-[#2563EB] cursor-pointer"
        >
          {{ tag }}
        </span>
      </div>
      
      <!-- 操作区域 -->
      <div class="flex items-center gap-[0.5rem]">
        <div class="flex items-center gap-[0.5rem] cursor-pointer">
          <img src="/public/icon/like.png" alt="" class="w-[1rem] h-[1rem]">
        </div>
        <div class="flex items-center gap-[0.5rem] cursor-pointer ml-[1.5rem]" @click="showComments(article.id)">
          <img src="/public/icon/comments.png" alt="" class="w-[1rem] h-[1rem]">
        </div>
        <div class="flex items-center gap-[0.5rem] cursor-pointer ml-[1.5rem]">
          <img src="/public/icon/collect.png" alt="" class="w-[1rem] h-[1rem]">
        </div>
        <div class="flex items-center gap-[0.5rem] cursor-pointer ml-[1.5rem]" @click="openComplaint(article.id)">
          <img src="/public/icon/warning.png" alt="" class="w-[1.25rem] h-[1.25rem]">
        </div>
      </div>
      
      <!-- 点赞人数 -->
      <div class="color-[#8b8e9d] text-[0.875rem] font-[Inter] font-normal leading-[1.25rem]" v-if="article.likeNames && article.likeNames.length > 0">
        <template v-for="(name,index) in article.likeNames">
          <span class="color-[#fda956] cursor-pointer">{{ name }}</span><span v-if="index != article.likeNames.length - 1">、</span>
        </template>
        觉得很赞
      </div>
      
      <!-- 评论回显 -->
      <div v-if="article.commentList && article.commentList.length > 0" class="flex flex-col gap-[1rem] mt-[1rem]">
        <div v-for="comment in article.commentList" :key="comment.id" class="flex flex-col gap-[0.5rem]">
          <div class="flex items-start gap-[0.5rem]">
            <img :src="comment.avatar" class="w-[2rem] h-[2rem] rounded-full" />
            <div class="flex flex-col gap-[0.25rem] w-full">
              <div class="flex items-center gap-[0.5rem]">
                <span class="text-[0.875rem] font-[Inter] font-medium leading-[1.25rem] text-[#000000]">{{ comment.author }}</span>
                <span class="text-[0.75rem] font-[Inter] font-normal leading-[1rem] text-[#6B7280]">{{ formatRelativeTime(comment.time) }}</span>
              </div>
              <div class="text-[0.875rem] font-[Inter] font-normal leading-[1.25rem] text-[#4B5563]">
                {{ comment.content }}
              </div>
              <div class="flex items-center gap-[1rem]">
                <div class="flex items-center gap-[0.25rem] cursor-pointer">
                  <img src="/public/icon/like.png" class="w-[0.875rem] h-[0.875rem]" />
                  <span class="text-[0.75rem] font-[Inter] font-normal leading-[1rem] text-[#6B7280]">{{ comment.likes }}</span>
                </div>
                <div class="flex items-center gap-[0.25rem] cursor-pointer" @click="toggleReplyInput(article.id, comment.id, comment.author, 0)">
                  <img src="/public/icon/comments.png" class="w-[0.875rem] h-[0.875rem]" />
                  <span class="text-[0.75rem] font-[Inter] font-normal leading-[1rem] text-[#6B7280]">回复</span>
                </div>
              </div>
              <!-- 回复输入框 -->
              <div v-if="activeReplyInfo.postId === article.id && activeReplyInfo.commentId === comment.id && activeReplyInfo.replyId === 0" class="mt-[0.5rem]">
                <CommentInput 
                  :post-id="article.id"
                  :comment-id="comment.id"
                  :reply-to="comment.author"
                  @submit="handleCommentSubmit"
                  @cancel="cancelReply"
                />
              </div>
            </div>
          </div>
          
          <!-- 回复评论 -->
          <div v-if="comment.replies && comment.replies.length > 0" class="ml-[2.5rem]">
            <div v-for="reply in comment.replies" :key="reply.id" class="flex items-start gap-[0.5rem] mt-[0.5rem]">
              <img :src="reply.avatar" class="w-[1.5rem] h-[1.5rem] rounded-full" />
              <div class="flex flex-col gap-[0.25rem] w-full">
                <div class="flex items-center gap-[0.5rem]">
                  <span class="text-[0.875rem] font-[Inter] font-medium leading-[1.25rem] text-[#000000]">{{ reply.author }}</span>
                  <span class="text-[0.75rem] font-[Inter] font-normal leading-[1rem] text-[#6B7280]">{{ formatRelativeTime(reply.time) }}</span>
                </div>
                <div class="text-[0.875rem] font-[Inter] font-normal leading-[1.25rem] text-[#4B5563]">
                  <span class="text-[#2563EB]">@{{ reply.replyTo }}</span> {{ reply.content }}
                </div>
                <div class="flex items-center gap-[1rem]">
                  <div class="flex items-center gap-[0.25rem] cursor-pointer">
                    <img src="/public/icon/like.png" class="w-[0.875rem] h-[0.875rem]" />
                    <span class="text-[0.75rem] font-[Inter] font-normal leading-[1rem] text-[#6B7280]">{{ reply.likes }}</span>
                  </div>
                  <div class="flex items-center gap-[0.25rem] cursor-pointer" @click="toggleReplyInput(article.id, comment.id, reply.author, reply.id)">
                    <img src="/public/icon/comments.png" class="w-[0.875rem] h-[0.875rem]" />
                    <span class="text-[0.75rem] font-[Inter] font-normal leading-[1rem] text-[#6B7280]">回复</span>
                  </div>
                </div>
                <!-- 回复的回复输入框 -->
                <div v-if="activeReplyInfo.postId === article.id && activeReplyInfo.commentId === comment.id && activeReplyInfo.replyId === reply.id" class="mt-[0.5rem]">
                  <CommentInput 
                    :post-id="article.id"
                    :comment-id="comment.id"
                    :reply-to="reply.author"
                    :reply-id="reply.id"
                    @submit="handleCommentSubmit"
                    @cancel="cancelReply"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 发布评论 -->
      <div v-if="article.showComment" class="mt-[1rem]">
        <CommentInput 
          :post-id="article.id"
          @submit="handleCommentSubmit"
        />
      </div>
      
      <!-- 文件下载弹窗 -->
      <FileDownload
        v-model="showFileDownload"
        :file-url="currentFileUrl"
        :file-name="currentFileName"
        @close="showFileDownload = false"
        @download="handleFileDownload"
      />
      
      <!-- 投诉弹窗 -->
      <Complaint 
        v-model="showComplaint"
        :post-id="currentPostId"
        @close="showComplaint = false"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits } from 'vue';
import { ElImage, ElDropdown, ElDropdownMenu, ElDropdownItem } from 'element-plus';
import { message } from '@/utils/message';
import { formatRelativeTime } from '@/utils/time';
import CommentInput from '@/components/CommentInput/index.vue';
import FileDownload from '@/components/FileDownload/index.vue';
import Complaint from '@/views/Forum/index/components/Complaint.vue';

// 定义文章类型
interface Article {
  id: number;
  author: string;
  authorAvatar: string;
  authorLevel: string;
  title: string;
  description: string;
  releaseTime: string;
  comment: number;
  like: number;
  collect: number;
  tags: string[];
  images?: string[];
  files?: string[];
  likeNames?: string[];
  showComment?: boolean;
  commentList?: any[];
}

const props = withDefaults(defineProps<{
  article: Article;
  border?: boolean;
}>(), {
  border: true
});

// 是否为管理员
const isAdmin = ref(true);

// 文件下载相关
const showFileDownload = ref(false);
const currentFileUrl = ref('');
const currentFileName = ref('');

// 投诉相关
const showComplaint = ref(false);
const currentPostId = ref(0);

// 回复信息
const activeReplyInfo = ref({
  postId: 0,
  commentId: 0,
  replyTo: '',
  replyId: 0
});

// 处理查看文章详情
const handlePostClick = (id: number) => {
  window.open(`/forum/details/${id}`, '_blank');
};

// 处理作者点击
const handleAuthorClick = (author: string) => {
  console.log('查看作者信息:', author);
};

// 处理下拉菜单命令
interface CommandPayload {
  type: string;
  id: number;
}

const handleCommand = (command: CommandPayload) => {
  const { type, id } = command;
  
  switch (type) {
    case 'changeCategory':
      console.log('修改分类', id);
      break;
    case 'addTag':
      console.log('添加标签', id);
      break;
    case 'setTop':
      console.log('设为置顶', id);
      break;
    case 'setEssence':
      console.log('设为精华/申请加精', id);
      break;
    case 'collect':
      console.log('收藏', id);
      break;
    case 'takeDown':
      console.log('下架', id);
      break;
    case 'complaint':
      console.log('投诉', id);
      openComplaint(id);
      break;
    default:
      break;
  }
};

// 展开评论
const showComments = (id: number) => {
  if (props.article.id === id) {
    props.article.showComment = !props.article.showComment;
  }
};

// 打开投诉弹窗
const openComplaint = (id: number) => {
  currentPostId.value = id;
  showComplaint.value = true;
};

// 处理文件点击
const handleFileClick = (fileUrl: string) => {
  console.log('点击文件:', fileUrl);
  currentFileUrl.value = fileUrl;
  currentFileName.value = getFileName(fileUrl);
  showFileDownload.value = true;
};

// 处理文件下载
const handleFileDownload = (fileUrl: string) => {
  console.log('下载文件:', fileUrl);
  message.success('开始下载文件');
};

// 获取文件名
const getFileName = (fileUrl: string) => {
  return fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
};

// 获取文件图标
const getFileIcon = (fileUrl: string) => {
  const fileName = getFileName(fileUrl);
  const extension = fileName.split('.').pop()?.toLowerCase() || '';
  
  switch (extension) {
    case 'pdf':
      return '/public/icon/pdf.png';
    case 'doc':
    case 'docx':
      return '/public/icon/word.png';
    case 'xls':
    case 'xlsx':
      return '/public/icon/excel.png';
    case 'ppt':
    case 'pptx':
      return '/public/icon/ppt.png';
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
    case 'webp':
      return '/public/icon/image.png';
    case 'mp4':
    case 'avi':
    case 'mov':
    case 'wmv':
      return '/public/icon/video.png';
    case 'mp3':
    case 'wav':
    case 'ogg':
      return '/public/icon/audio.png';
    case 'zip':
    case 'rar':
    case '7z':
    case 'tar':
    case 'gz':
      return '/public/icon/zip.png';
    case 'txt':
      return '/public/icon/text.png';
    case 'html':
    case 'css':
    case 'js':
    case 'ts':
    case 'jsx':
    case 'tsx':
    case 'vue':
      return '/public/icon/code.png';
    default:
      return '/public/icon/file.png';
  }
};

// 切换回复输入框
const toggleReplyInput = (postId: number, commentId: number, replyTo: string, replyId?: number) => {
  // 如果已经是当前回复，则关闭
  if (activeReplyInfo.value.postId === postId && 
      activeReplyInfo.value.commentId === commentId && 
      activeReplyInfo.value.replyTo === replyTo &&
      activeReplyInfo.value.replyId === (replyId || 0)) {
    cancelReply();
    return;
  }
  
  // 设置当前回复信息
  activeReplyInfo.value = {
    postId,
    commentId,
    replyTo,
    replyId: replyId || 0
  };
};

// 取消回复
const cancelReply = () => {
  activeReplyInfo.value = {
    postId: 0,
    commentId: 0,
    replyTo: '',
    replyId: 0
  };
};

// 处理评论提交
interface CommentData {
  content: string;
  postId?: number;
  commentId?: number;
  replyTo?: string;
  replyId?: number;
  time: string;
}

const handleCommentSubmit = (data: CommentData) => {
  console.log('提交评论数据:', data);
  
  try {
    if (props.article.id !== data.postId) {
      throw new Error(`文章ID不匹配`);
    }
    
    // 如果是回复评论
    if (data.commentId) {
      const targetComment = props.article.commentList?.find(comment => comment.id === data.commentId);
      if (!targetComment) {
        throw new Error(`未找到ID为 ${data.commentId} 的评论`);
      }
      
      // 确保replies数组存在
      if (!targetComment.replies) {
        targetComment.replies = [];
      }
      
      // 生成新回复
      const newReply = {
        id: Date.now(), // 使用时间戳作为临时ID
        author: '当前用户', // 这里应该使用实际的用户信息
        avatar: '/public/images/avatar.png', // 这里应该使用实际的用户头像
        content: data.content,
        time: data.time,
        likes: 0,
        replyTo: data.replyTo || ''
      };
      
      // 添加回复
      targetComment.replies.push(newReply);
      message.success('回复成功');
    } else {
      // 确保commentList数组存在
      if (!props.article.commentList) {
        props.article.commentList = [];
      }
      
      // 添加新评论
      const newComment = {
        id: Date.now(), // 使用时间戳作为临时ID
        author: '当前用户', // 这里应该使用实际的用户信息
        avatar: '/public/images/avatar.png', // 这里应该使用实际的用户头像
        content: data.content,
        time: data.time,
        likes: 0,
        replyTo: '', // 添加缺少的replyTo字段
        replies: []
      };
      
      // 添加评论
      props.article.commentList.push(newComment);
      message.success('评论成功');
    }
    
    // 关闭回复框
    cancelReply();
  } catch (error) {
    console.error('评论/回复失败:', error);
    message.error(error instanceof Error ? error.message : '评论失败');
  }
};
</script>

<style scoped>
</style> 